import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dartz/dartz.dart';

import '../repositories/auth_repository.dart';
import '../../models/auth_models.dart';

/// 认证状态
class AuthState {
  const AuthState({
    this.user,
    this.isLoading = false,
    this.error,
    this.verificationId,
  });

  final UserInfo? user;
  final bool isLoading;
  final String? error;
  final String? verificationId;

  bool get isAuthenticated => user != null;

  AuthState copyWith({
    UserInfo? user,
    bool? isLoading,
    String? error,
    String? verificationId,
  }) {
    return AuthState(
      user: user ?? this.user,
      isLoading: isLoading ?? this.isLoading,
      error: error,
      verificationId: verificationId ?? this.verificationId,
    );
  }

  @override
  String toString() => 'AuthState(user: $user, isLoading: $isLoading, error: $error)';
}

/// 认证状态管理
class AuthNotifier extends StateNotifier<AuthState> {
  AuthNotifier(this._authRepository) : super(const AuthState()) {
    // 延迟初始化以避免在Provider构建期间修改状态
    Future(() => _initialize());
  }

  final AuthRepository _authRepository;

  /// 初始化认证状态
  Future<void> _initialize() async {
    state = state.copyWith(isLoading: true);
    
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('auth_token'); // 🔥 修复：使用与AuthService相同的key
      
      if (token != null) {
        // 验证Token有效性
        final result = await _authRepository.validateToken();
        result.fold(
          (failure) {
            // 如果是401错误，可能是后端禁用了认证，使用默认用户
            if (failure.message.contains('401') || failure.message.contains('未认证')) {
              // 创建默认用户状态（后端禁用认证时）
              final defaultUser = UserInfo(
                id: 1,
                username: 'default_user',
                phoneNumber: '13900139000',
                role: 'user',
                status: 'active',
                nickname: '默认用户',
              );
              state = state.copyWith(user: defaultUser, isLoading: false);
            } else {
              // 真正的Token无效，清除本地存储
              _clearTokens();
              state = state.copyWith(isLoading: false, error: failure.message);
            }
          },
          (user) {
            state = state.copyWith(user: user, isLoading: false);
          },
        );
      } else {
        // 没有token，但检查后端是否禁用认证
        final result = await _authRepository.validateToken();
        if (result.isLeft()) {
          final failure = result.fold((l) => l, (r) => null)!;
          // 如果是401错误，可能是后端禁用了认证，使用默认用户
          if (failure.message.contains('401') || failure.message.contains('未认证')) {
            // 创建默认用户状态（后端禁用认证时）
            final defaultUser = UserInfo(
              id: 1,
              username: 'default_user',
              phoneNumber: '13900139000',
              role: 'user',
              status: 'active',
              nickname: '默认用户',
            );
            // 保存一个默认token
            await _saveTokens('default_token', null);
            state = state.copyWith(user: defaultUser, isLoading: false);
          } else {
            // 需要登录
            state = state.copyWith(isLoading: false);
          }
        } else {
          // 不应该到达这里，因为没有token
          state = state.copyWith(isLoading: false);
        }
      }
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
    }
  }

  /// 发送验证码
  Future<void> sendVerificationCode(String phoneNumber) async {
    state = state.copyWith(isLoading: true, error: null);
    
    final result = await _authRepository.sendVerificationCode(phoneNumber);
    result.fold(
      (failure) {
        state = state.copyWith(isLoading: false, error: failure.message);
      },
      (response) {
        state = state.copyWith(
          isLoading: false,
          verificationId: response.verificationId,
        );
      },
    );
  }

  /// 验证码登录
  Future<void> verifyCodeAndLogin({
    required String phoneNumber,
    required String code,
    required String verificationId,
  }) async {
    state = state.copyWith(isLoading: true, error: null);
    
    final result = await _authRepository.verifyCodeAndLogin(
      phoneNumber: phoneNumber,
      code: code,
      verificationId: verificationId,
    );
    
    if (result.isLeft()) {
      // 登录失败
      final failure = result.fold((l) => l, (r) => null)!;
      state = state.copyWith(isLoading: false, error: failure.message);
    } else {
      // 登录成功
      final loginResponse = result.fold((l) => null, (r) => r)!;
      // 🔥 修复：先更新state，再保存tokens（这样_saveTokens能访问到state.user）
      state = state.copyWith(user: loginResponse.user, isLoading: false);
      await _saveTokens(loginResponse.token, loginResponse.refreshToken);
    }
  }

  /// 刷新用户信息
  Future<void> refreshUserInfo() async {
    if (!state.isAuthenticated) return;
    
    final result = await _authRepository.getUserInfo();
    result.fold(
      (failure) {
        // 可以选择不更新状态，或者显示错误
      },
      (user) {
        state = state.copyWith(user: user);
      },
    );
  }

  /// 登出
  Future<void> logout() async {
    state = state.copyWith(isLoading: true);
    
    await _authRepository.logout();
    // 无论API调用是否成功，都清除本地状态
    await _clearTokens();
    state = const AuthState();
  }

  /// 清除错误
  void clearError() {
    state = state.copyWith(error: null);
  }

  /// 保存Token和用户信息
  Future<void> _saveTokens(String token, String? refreshToken) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('auth_token', token); // 🔥 修复：使用与AuthService相同的key
    if (refreshToken != null) {
      await prefs.setString('refreshToken', refreshToken);
    }
    
    // 🔥 新增：同步保存用户信息，确保AuthService能读取
    if (state.user != null) {
      await prefs.setString('user_id', state.user!.id.toString());
      await prefs.setString('phone_number', state.user!.phoneNumber);
      await prefs.setString('username', state.user!.username);
    }
  }

  /// 清除Token和用户信息
  Future<void> _clearTokens() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('auth_token'); // 🔥 修复：使用与AuthService相同的key
    await prefs.remove('refreshToken');
    // 🔥 新增：同时清除用户信息
    await prefs.remove('user_id');
    await prefs.remove('phone_number');
    await prefs.remove('username');
  }
}

/// 认证状态Provider
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>(
  (ref) => AuthNotifier(ref.watch(authRepositoryProvider)),
);

/// 便捷的Provider
final isAuthenticatedProvider = Provider<bool>(
  (ref) => ref.watch(authProvider).isAuthenticated,
);

final currentUserProvider = Provider<UserInfo?>(
  (ref) => ref.watch(authProvider).user,
);
